import pygame
import random
import os
import math
import time


# 初始化Pygame
pygame.init()


# 游戏常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
CARD_WIDTH = 55
CARD_HEIGHT = 70
SPACING = 30
LAYER_OFFSET = 5
GRID_ROWS = 4
GRID_COLS = 4
SLOT_ROWS = 1
SLOT_COLS = 7
UNDO_MAX_STORAGE = 3  # 最大可存储的撤销次数
ELIMINATE_TOTAL_STEPS = 20
MOVE_TOTAL_STEPS = 60
BACKGROUND_SWITCH_INTERVAL = 200  # 背景切换间隔(毫秒)
THIEF_APPEAR_INTERVAL = 5000  # 飞贼出现间隔(毫秒)
THIEF_DROP_SPEED = 2  # 飞贼降落速度
THIEF_STEAL_TIME = 1000  # 飞贼偷取卡片所需时间
UMBRELLA_MAX_SIZE = 240  # 萝卜保护伞最大尺寸（修改为原2倍）
UMBRELLA_GROW_SPEED = 5  # 萝卜保护伞变大速度（加快）
UMBRELLA_EFFECT_DURATION = 2000  # 萝卜保护伞效果持续时间(毫秒)


# 新增洗牌功能常量
SHUFFLE_MAX_TIMES = 3  # 最大洗牌次数
SHUFFLE_BUTTON_WIDTH = 50
SHUFFLE_BUTTON_HEIGHT = 50
SHUFFLE_BUTTON_LEFT = 20




# 重新开始按钮常量
RESTART_BUTTON_SIZE = 60  # 改为正方形按钮
RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_SIZE) // 2
RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50
RESTART_BUTTON_SCALE_SPEED = 0.02  # 缩放速度
RESTART_BUTTON_MAX_SCALE = 1.1  # 最大缩放比例
RESTART_BUTTON_MIN_SCALE = 0.9  # 最小缩放比例


# 颜色定义
BG_COLOR = (255, 255, 255)
COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (128, 0, 128),  # 紫
]
PARTICLE_COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (255, 0, 255),  # 紫
    (0, 255, 255),  # 青
    (255, 165, 0),  # 橙
    (255, 215, 0),  # 金
]


# 计算布局
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100


slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20


# 初始化游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")




# 加载资源
def load_image(path, width, height):
    try:
        img = pygame.image.load(path)
        return pygame.transform.scale(img, (width, height))
    except Exception as e:
        print(f"图片加载失败: {e}")
        return None




# 背景管理器
class BackgroundManager:
    def __init__(self):
        self.backgrounds = []
        self.current_index = 0
        self.last_switch_time = pygame.time.get_ticks()


    def load_backgrounds(self):
        """加载所有背景图片"""
        try:
            image_folder = os.path.join("image")
            # 加载多张背景图片
            for i in range(2):  # 假设加载2张背景图
                bg_path = os.path.join(image_folder, f"back{i}.png")
                bg_img = load_image(bg_path, SCREEN_WIDTH, SCREEN_HEIGHT)
                if bg_img:
                    self.backgrounds.append(bg_img)
                    print(f"背景图片 {os.path.basename(bg_path)} 加载成功")


            if not self.backgrounds:
                # 如果没有找到背景图片，使用默认纯色背景
                print("警告: 没有找到任何背景图片")
        except Exception as e:
            print(f"背景图片加载失败: {e}")


    def get_current_background(self):
        """获取当前背景图片"""
        if self.backgrounds:
            return self.backgrounds[self.current_index]
        return None


    def switch_background(self):
        """切换到下一张背景图片"""
        if len(self.backgrounds) > 1:
            self.current_index = (self.current_index + 1) % len(self.backgrounds)
            print(f"切换到背景图片 {self.current_index + 1}")


    def update(self):
        """定时更新背景图片"""
        current_time = pygame.time.get_ticks()
        if current_time - self.last_switch_time > BACKGROUND_SWITCH_INTERVAL:
            self.switch_background()
            self.last_switch_time = current_time




# 加载撤销按钮图片
undo_button_img = load_image(os.path.join("image", "tile8.png"), 50, 50)
UNDO_BUTTON_WIDTH = undo_button_img.get_width() if undo_button_img else 100
UNDO_BUTTON_HEIGHT = undo_button_img.get_height() if undo_button_img else 50
UNDO_BUTTON_LEFT = 20
UNDO_BUTTON_TOP = 20


# 加载洗牌按钮图片
shuffle_button_img = load_image(os.path.join("image", "shuffle.png"), 50, 50)  # 请确保有shuffle.png图片
SHUFFLE_BUTTON_WIDTH = shuffle_button_img.get_width() if shuffle_button_img else 100
SHUFFLE_BUTTON_HEIGHT = shuffle_button_img.get_height() if shuffle_button_img else 50
SHUFFLE_BUTTON_LEFT = 20
SHUFFLE_BUTTON_TOP = 20 + UNDO_BUTTON_HEIGHT + 20  # 在撤销按钮下方


# **新增萝卜保护伞常量（移到此处，此时UNDO和SHUFFLE的高度已定义）**
UMBRELLA_BUTTON_WIDTH = 50
UMBRELLA_BUTTON_HEIGHT = 50
UMBRELLA_BUTTON_LEFT = 20
UMBRELLA_BUTTON_TOP = 20 + UNDO_BUTTON_HEIGHT + SHUFFLE_BUTTON_HEIGHT + 30  # 在洗牌按钮下方


# 加载萝卜保护伞按钮图片
umbrella_button_img = load_image(os.path.join("image", "san.PNG"), UMBRELLA_BUTTON_WIDTH, UMBRELLA_BUTTON_HEIGHT)


# 加载重新开始按钮图片 - 调整为正方形
restart_button_img = load_image(os.path.join("image", "chongkai.PNG"), RESTART_BUTTON_SIZE, RESTART_BUTTON_SIZE)


# 加载槽位背景图像
slot_bg_img = load_image(os.path.join("image", "back2.png"), slot_width + 20, SLOT_HEIGHT + 20)


# 加载卡片图片
card_images = []
for i in range(5):
    tile_path = os.path.join("image", f"tile{i}.png" if i > 0 else "tile.png")
    img = load_image(tile_path, CARD_WIDTH, CARD_HEIGHT)
    if img:
        card_images.append(img)


if not card_images:
    print("警告: 没有找到任何卡片图片，将使用纯色代替")


# 加载飞贼图片
thief_img = load_image(os.path.join("image", "feizei.PNG"), CARD_WIDTH + 10, CARD_HEIGHT + 10)
THIEF_WIDTH = thief_img.get_width() if thief_img else 70
THIEF_HEIGHT = thief_img.get_height() if thief_img else 80


# 加载萝卜保护伞图片
umbrella_img = load_image(os.path.join("image", "san.PNG"), UMBRELLA_MAX_SIZE, UMBRELLA_MAX_SIZE)




# 礼炮粒子系统
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.radius = random.randint(2, 5)
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(2, 5)
        self.vx = math.cos(angle) * speed
        self.vy = math.sin(angle) * speed
        self.gravity = 0.1
        self.life = 30  # 粒子生命周期


    def update(self):
        self.vy += self.gravity
        self.x += self.vx
        self.y += self.vy
        self.life -= 1
        return self.life > 0


    def draw(self, surface):
        alpha = int(255 * (self.life / 30))
        s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(s, self.color + (alpha,), (self.radius, self.radius), self.radius)
        surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))




# 飞贼类
class Thief:
    def __init__(self, row, col):
        self.row = row
        self.col = col
        self.x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
        self.y = -THIEF_HEIGHT  # 初始位置在屏幕外
        self.target_y = GRID_TOP + row * (CARD_HEIGHT + SPACING) - LAYER_OFFSET * 2
        self.state = "dropping"  # dropping, stealing, leaving, repelled
        self.steal_start_time = 0
        self.stolen_card = None
        self.repelled_speed = 0  # 被击退的速度


    def update(self, game_state):
        if self.state == "dropping":
            self.y += THIEF_DROP_SPEED
            if self.y >= self.target_y:
                self.y = self.target_y
                # 检查目标位置是否有卡片
                if len(game_state.grid[self.row][self.col]) > 0:
                    self.stolen_card = game_state.grid[self.row][self.col].pop()
                    self.state = "stealing"
                    self.steal_start_time = pygame.time.get_ticks()
                else:
                    self.state = "leaving"
        elif self.state == "stealing":
            if pygame.time.get_ticks() - self.steal_start_time > THIEF_STEAL_TIME:
                self.state = "leaving"
        elif self.state == "leaving":
            self.y -= THIEF_DROP_SPEED * 1.5
            if self.y < -THIEF_HEIGHT:
                return False  # 飞贼已离开屏幕
        elif self.state == "repelled":
            self.y -= THIEF_DROP_SPEED * 10  # 加快击退速度（原5倍，现10倍）
            if self.y < -THIEF_HEIGHT:
                return False  # 飞贼已离开屏幕
        return True


    def draw(self, surface):
        if thief_img:
            if self.state == "repelled":
                # 飞贼被击退时旋转180度
                rotated_img = pygame.transform.rotate(thief_img, 180)
                surface.blit(rotated_img, (self.x, self.y))
            else:
                surface.blit(thief_img, (self.x, self.y))
        else:
            # 如果没有图片，绘制一个简单的矩形代替
            color = (128, 0, 0) if self.state != "repelled" else (255, 100, 100)
            pygame.draw.rect(surface, color, (self.x, self.y, THIEF_WIDTH, THIEF_HEIGHT))
            pygame.draw.rect(surface, (255, 255, 255), (self.x, self.y, THIEF_WIDTH, THIEF_HEIGHT), 2)




# 萝卜保护伞效果类
class UmbrellaEffect:
    def __init__(self):
        self.active = False
        self.size = 0
        self.max_size = UMBRELLA_MAX_SIZE  # 使用新常量
        self.grow_speed = UMBRELLA_GROW_SPEED  # 使用新常量
        self.center_x = SCREEN_WIDTH // 2
        self.center_y = SCREEN_HEIGHT // 2
        self.start_time = 0
        self.duration = UMBRELLA_EFFECT_DURATION


    def activate(self):
        self.active = True
        self.size = 0
        self.start_time = pygame.time.get_ticks()


    def update(self, game_state):
        if not self.active:
            return


        # 更新保护伞大小
        if self.size < self.max_size:
            self.size += self.grow_speed
        else:
            # 检查效果是否已过期
            if pygame.time.get_ticks() - self.start_time > self.duration:
                self.active = False
                return


        # 检查并击退范围内的飞贼（全图范围）
        for thief in game_state.thieves:
            if self.is_thief_in_range(thief):
                if thief.state != "repelled":
                    thief.state = "repelled"
                    thief.repelled_speed = THIEF_DROP_SPEED * 10  # 加快击退速度


    def is_thief_in_range(self, thief):
        # 直接返回True（全图范围）
        return True


    def draw(self, surface):
        if not self.active:
            return


        # 绘制萝卜保护伞
        if umbrella_img:
            # 根据当前大小缩放图片
            scaled_img = pygame.transform.scale(umbrella_img, (int(self.size), int(self.size)))
            img_rect = scaled_img.get_rect(center=(self.center_x, self.center_y))
            surface.blit(scaled_img, img_rect)
        else:
            # 如果没有图片，绘制一个简单的圆形代替
            pygame.draw.circle(surface, (0, 150, 0), (self.center_x, self.center_y), int(self.size // 2), 3)




# 重新开始按钮类
class RestartButton:
    def __init__(self):
        self.base_image = restart_button_img
        self.current_scale = 1.0
        self.scale_direction = 1  # 1 表示放大, -1 表示缩小


        # 如果没有加载到图片，创建一个默认的正方形按钮
        if not self.base_image:
            self.base_image = pygame.Surface((RESTART_BUTTON_SIZE, RESTART_BUTTON_SIZE), pygame.SRCALPHA)
            self.base_image.fill((0, 150, 0))  # 绿色背景
            font = pygame.font.Font(None, 24)
            text = font.render("RESTART", True, (255, 255, 255))
            text_rect = text.get_rect(center=(RESTART_BUTTON_SIZE // 2, RESTART_BUTTON_SIZE // 2))
            self.base_image.blit(text, text_rect)


        self.current_image = self.base_image
        self.rect = self.base_image.get_rect(
            center=(RESTART_BUTTON_LEFT + RESTART_BUTTON_SIZE // 2,
                    RESTART_BUTTON_TOP + RESTART_BUTTON_SIZE // 2))


    def update(self):
        """更新按钮的缩放状态"""
        self.current_scale += RESTART_BUTTON_SCALE_SPEED * self.scale_direction


        # 检查是否需要改变缩放方向
        if self.current_scale >= RESTART_BUTTON_MAX_SCALE:
            self.current_scale = RESTART_BUTTON_MAX_SCALE
            self.scale_direction = -1
        elif self.current_scale <= RESTART_BUTTON_MIN_SCALE:
            self.current_scale = RESTART_BUTTON_MIN_SCALE
            self.scale_direction = 1


        # 创建缩放后的图像
        new_width = int(RESTART_BUTTON_SIZE * self.current_scale)
        new_height = int(RESTART_BUTTON_SIZE * self.current_scale)
        self.current_image = pygame.transform.scale(self.base_image, (new_width, new_height))


        # 更新位置，保持居中
        self.rect = self.current_image.get_rect(center=self.rect.center)


    def draw(self, surface):
        """绘制按钮"""
        surface.blit(self.current_image, self.rect)


    def is_clicked(self, pos):
        """检查按钮是否被点击"""
        return self.rect.collidepoint(pos)




# 游戏状态
class GameState:
    def __init__(self):
        self.slots = []
        self.score = 0
        self.game_over = False
        self.game_won = False
        self.undo_stack = []
        self.moving_card = None
        self.move_steps = 0
        self.eliminating_cards = []
        self.eliminate_steps = 0
        self.undo_available = 0  # 可用的撤销次数
        self.elimination_count = 0  # 消除计数
        self.particles = []
        self.grid = self._initialize_grid()
        self.shuffle_times = SHUFFLE_MAX_TIMES  # 剩余洗牌次数
        self.thieves = []  # 飞贼列表
        self.last_thief_time = pygame.time.get_ticks()  # 上次生成飞贼的时间
        self.umbrella_charges = 0  # 萝卜保护伞可用次数
        self.umbrella_effect = UmbrellaEffect()  # 萝卜保护伞效果


    def _initialize_grid(self):
        grid = []
        for row in range(GRID_ROWS):
            grid_row = []
            for col in range(GRID_COLS):
                layers = random.randint(3, 5)
                max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
                stack = [(random.randint(0, max_card_type), layer) for layer in range(layers)]
                stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
                grid_row.append(stack)
            grid.append(grid_row)
        return grid


    def check_victory(self):
        """检查是否胜利"""
        for row in self.grid:
            for stack in row:
                if len(stack) > 0:
                    return False
        return len(self.slots) == 0


    def create_fireworks(self, x, y):
        """创建礼炮爆炸效果"""
        for _ in range(50):  # 每个卡片产生50个粒子
            color = random.choice(PARTICLE_COLORS)
            self.particles.append(Particle(x, y, color))


    def update_particles(self):
        """更新礼炮粒子"""
        self.particles = [p for p in self.particles if p.update()]


    def gain_undo_chance(self):
        """增加一次撤销机会"""
        if self.undo_available < UNDO_MAX_STORAGE:
            self.undo_available += 1
            print(f"获得一次撤销机会! 当前可用撤销次数: {self.undo_available}")


    def gain_umbrella_charge(self):
        """增加一次萝卜保护伞使用次数"""
        self.umbrella_charges += 1
        print(f"获得一次萝卜保护伞使用次数! 当前可用次数: {self.umbrella_charges}")


    def use_umbrella(self):
        """使用萝卜保护伞"""
        if self.umbrella_charges > 0 and not self.umbrella_effect.active:
            self.umbrella_charges -= 1
            self.umbrella_effect.activate()
            print(f"使用萝卜保护伞! 剩余次数: {self.umbrella_charges}")
            return True
        return False


    def shuffle_grid(self):
        """洗牌功能：重新排列网格中的卡片"""
        if self.shuffle_times <= 0:
            return False


        # 收集所有卡片
        all_cards = []
        for row in self.grid:
            for stack in row:
                all_cards.extend(stack)
                stack.clear()


        # 随机打乱卡片顺序
        random.shuffle(all_cards)


        # 重新分配卡片到网格
        index = 0
        for row in range(GRID_ROWS):
            for col in range(GRID_COLS):
                # 每个位置分配3-5张卡片
                layers = random.randint(3, 5)
                for _ in range(layers):
                    if index < len(all_cards):
                        self.grid[row][col].append(all_cards[index])
                        index += 1


        # 减少洗牌次数
        self.shuffle_times -= 1
        print(f"洗牌成功! 剩余洗牌次数: {self.shuffle_times}")
        return True


    def reset_game(self):
        """重置游戏状态"""
        self.slots = []
        self.score = 0
        self.game_over = False
        self.game_won = False
        self.undo_stack = []
        self.moving_card = None
        self.move_steps = 0
        self.eliminating_cards = []
        self.eliminate_steps = 0
        self.undo_available = 0
        self.elimination_count = 0
        self.particles = []
        self.grid = self._initialize_grid()
        self.shuffle_times = SHUFFLE_MAX_TIMES
        self.thieves = []
        self.last_thief_time = pygame.time.get_ticks()
        self.umbrella_charges = 0
        self.umbrella_effect = UmbrellaEffect()


    def update_thieves(self):
        """更新飞贼状态"""
        # 更新保护伞效果
        self.umbrella_effect.update(self)


        # 移除已离开的飞贼
        self.thieves = [thief for thief in self.thieves if thief.update(self)]


        # 检查是否需要生成新飞贼
        current_time = pygame.time.get_ticks()
        if current_time - self.last_thief_time > THIEF_APPEAR_INTERVAL and not self.game_over:
            # 寻找有卡片的位置
            available_positions = []
            for row in range(GRID_ROWS):
                for col in range(GRID_COLS):
                    if len(self.grid[row][col]) > 0:
                        available_positions.append((row, col))


            # 如果有可用位置，随机选择一个生成飞贼
            if available_positions:
                row, col = random.choice(available_positions)
                self.thieves.append(Thief(row, col))
                self.last_thief_time = current_time




# 渲染函数
def render_background(state, background_manager):
    """渲染背景"""
    current_bg = background_manager.get_current_background()
    if current_bg:
        screen.blit(current_bg, (0, 0))
    else:
        screen.fill(BG_COLOR)




def render_grid(state):
    """渲染卡片堆"""
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            if len(state.grid[row][col]) > 0:
                top_card_layer = state.grid[row][col][-1][1]
                for card_type, card_layer in state.grid[row][col]:
                    y_offset = y - (top_card_layer - card_layer) * LAYER_OFFSET
                    if card_images:
                        screen.blit(card_images[card_type], (x, y_offset))
                    else:
                        pygame.draw.rect(screen, COLORS[card_type], (x, y_offset, CARD_WIDTH, CARD_HEIGHT))




def render_slot_background():
    """渲染槽位背景"""
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(screen, (200, 200, 200),
                         (SLOT_LEFT - 5, SLOT_TOP - 5,
                          slot_width + 10, SLOT_HEIGHT + 10),
                         border_radius=10)




def render_slots(state):
    """渲染槽位中的卡片"""
    for i, card in enumerate(state.slots):
        # 检查是否是正在消除的卡片
        is_eliminating = False
        for ec in state.eliminating_cards:
            if ec[1] == SLOT_LEFT + i * (CARD_WIDTH + 5) and ec[2] == SLOT_TOP:
                is_eliminating = True
                break


        # 检查是否是正在移动的卡片，如果是则不渲染，由移动动画处理
        is_moving = False
        if state.moving_card:
            card_type, _, _, target_x, _ = state.moving_card
            slot_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_type == card and abs(target_x - slot_x) < 1:  # 允许小误差
                is_moving = True


        if not is_eliminating and not is_moving:
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_images:
                screen.blit(card_images[card], (x, SLOT_TOP))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))




def render_animations(state):
    """渲染各种动画效果"""
    # 渲染移动中的卡片
    if state.moving_card:
        card, start_x, start_y, target_x, target_y = state.moving_card
        current_x = start_x + (target_x - start_x) * state.move_steps / MOVE_TOTAL_STEPS
        current_y = start_y + (target_y - start_y) * state.move_steps / MOVE_TOTAL_STEPS


        if card_images:
            screen.blit(card_images[card], (current_x, current_y))
        else:
            pygame.draw.rect(screen, COLORS[card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))


    # 渲染礼炮粒子
    for particle in state.particles:
        particle.draw(screen)


    # 渲染消除动画
    if state.eliminating_cards:
        progress = state.eliminate_steps / ELIMINATE_TOTAL_STEPS
        scale = 1.0 - progress  # 卡片缩小因子
        alpha = 255 * (1.0 - progress)  # 卡片透明度


        for card, x, y in state.eliminating_cards:
            if card_images:
                # 创建临时缩放图像
                temp_width = int(CARD_WIDTH * scale)
                temp_height = int(CARD_HEIGHT * scale)
                scaled_img = pygame.transform.scale(card_images[card], (temp_width, temp_height))


                # 创建半透明表面
                s = pygame.Surface((temp_width, temp_height), pygame.SRCALPHA)
                s.blit(scaled_img, (0, 0))
                s.set_alpha(int(alpha))


                screen.blit(s, (x + (CARD_WIDTH - temp_width) // 2, y + (CARD_HEIGHT - temp_height) // 2))
            else:
                # 绘制彩色矩形
                s = pygame.Surface((int(CARD_WIDTH * scale), int(CARD_HEIGHT * scale)), pygame.SRCALPHA)
                s.fill(COLORS[card] + (int(alpha),))  # 添加透明度
                screen.blit(s, (x + (CARD_WIDTH - int(CARD_WIDTH * scale)) // 2,
                                y + (CARD_HEIGHT - int(CARD_HEIGHT * scale)) // 2))


    # 渲染飞贼
    for thief in state.thieves:
        thief.draw(screen)


    # 渲染萝卜保护伞效果
    state.umbrella_effect.draw(screen)




def render_status(state, restart_button):
    """渲染状态信息"""
    font = pygame.font.Font(None, 36)


    # 渲染分数
    text = font.render(f"Score: {state.score}", True, (0, 0, 0))
    screen.blit(text, (20, 20 + UNDO_BUTTON_HEIGHT + SHUFFLE_BUTTON_HEIGHT + UMBRELLA_BUTTON_HEIGHT + 30))


    # 渲染槽位容量提示
    capacity_text = font.render(f"{len(state.slots)}/{SLOT_COLS}", True, (100, 100, 100))
    screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))


    # 渲染撤销按钮
    if undo_button_img:
        screen.blit(undo_button_img, (UNDO_BUTTON_LEFT, UNDO_BUTTON_TOP))
    else:
        pygame.draw.rect(screen, (200, 0, 0),
                         (UNDO_BUTTON_LEFT, UNDO_BUTTON_TOP, UNDO_BUTTON_WIDTH, UNDO_BUTTON_HEIGHT))
    undo_text = font.render(f"{state.undo_available}", True, (255, 255, 255))
    screen.blit(undo_text, (UNDO_BUTTON_LEFT + UNDO_BUTTON_WIDTH - 15, UNDO_BUTTON_TOP - 5))


    # 渲染洗牌按钮
    if shuffle_button_img:
        screen.blit(shuffle_button_img, (SHUFFLE_BUTTON_LEFT, SHUFFLE_BUTTON_TOP))
    else:
        pygame.draw.rect(screen, (0, 128, 255),
                         (SHUFFLE_BUTTON_LEFT, SHUFFLE_BUTTON_TOP, SHUFFLE_BUTTON_WIDTH, SHUFFLE_BUTTON_HEIGHT))
    shuffle_text = font.render(f"{state.shuffle_times}", True, (255, 255, 255))
    screen.blit(shuffle_text, (SHUFFLE_BUTTON_LEFT + SHUFFLE_BUTTON_WIDTH - 15, SHUFFLE_BUTTON_TOP - 5))


    # 渲染萝卜保护伞按钮
    if umbrella_button_img:
        screen.blit(umbrella_button_img, (UMBRELLA_BUTTON_LEFT, UMBRELLA_BUTTON_TOP))
    else:
        pygame.draw.rect(screen, (0, 150, 0),
                         (UMBRELLA_BUTTON_LEFT, UMBRELLA_BUTTON_TOP, UMBRELLA_BUTTON_WIDTH, UMBRELLA_BUTTON_HEIGHT))
    umbrella_text = font.render(f"{state.umbrella_charges}", True, (255, 255, 255))
    screen.blit(umbrella_text, (UMBRELLA_BUTTON_LEFT + UMBRELLA_BUTTON_WIDTH - 15, UMBRELLA_BUTTON_TOP - 5))


    # 渲染游戏结束信息
    if state.game_over:
        text = font.render("YOU WIN!" if state.game_won else "GAME OVER!",
                           True, (0, 255, 0) if state.game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))


        # 渲染重新开始按钮
        restart_button.draw(screen)




# 初始化背景管理器
background_manager = BackgroundManager()
background_manager.load_backgrounds()


# 初始化游戏状态
game_state = GameState()


# 初始化重新开始按钮
restart_button = RestartButton()


# 主循环
clock = pygame.time.Clock()
running = True


while running:
    # 更新背景管理器
    background_manager.update()


    # 更新重新开始按钮
    if game_state.game_over:
        restart_button.update()


    # 更新飞贼
    game_state.update_thieves()


    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()


            # 游戏结束状态下检查重新开始按钮
            if game_state.game_over:
                if restart_button.is_clicked((x, y)):
                    game_state.reset_game()
                    continue


            # 游戏进行中处理其他按钮
            if not game_state.game_over and not game_state.eliminating_cards:
                # 检查是否点击了撤销按钮
                if (
                        UNDO_BUTTON_LEFT <= x <= UNDO_BUTTON_LEFT + UNDO_BUTTON_WIDTH
                        and UNDO_BUTTON_TOP <= y <= UNDO_BUTTON_TOP + UNDO_BUTTON_HEIGHT
                        and game_state.undo_available > 0
                ):
                    if game_state.undo_stack:
                        prev_grid, prev_slots, prev_score = game_state.undo_stack.pop()
                        game_state.grid[:] = [row[:] for row in prev_grid]
                        game_state.slots[:] = prev_slots[:]
                        game_state.score = prev_score
                        game_state.undo_available -= 1  # 使用一次撤销
                # 检查是否点击了洗牌按钮
                elif (
                        SHUFFLE_BUTTON_LEFT <= x <= SHUFFLE_BUTTON_LEFT + SHUFFLE_BUTTON_WIDTH
                        and SHUFFLE_BUTTON_TOP <= y <= SHUFFLE_BUTTON_TOP + SHUFFLE_BUTTON_HEIGHT
                        and game_state.shuffle_times > 0
                ):
                    # 记录当前状态用于撤销
                    game_state.undo_stack.append(
                        ([row[:] for row in game_state.grid], game_state.slots[:], game_state.score))
                    game_state.shuffle_grid()
                # 检查是否点击了萝卜保护伞按钮
                elif (
                        UMBRELLA_BUTTON_LEFT <= x <= UMBRELLA_BUTTON_LEFT + UMBRELLA_BUTTON_WIDTH
                        and UMBRELLA_BUTTON_TOP <= y <= UMBRELLA_BUTTON_TOP + UMBRELLA_BUTTON_HEIGHT
                ):
                    # 记录当前状态用于撤销
                    game_state.undo_stack.append(
                        ([row[:] for row in game_state.grid], game_state.slots[:], game_state.score))
                    game_state.use_umbrella()
                else:
                    # 记录当前状态用于撤销
                    game_state.undo_stack.append(
                        ([row[:] for row in game_state.grid], game_state.slots[:], game_state.score))
                    # 计算点击位置
                    for row in range(GRID_ROWS):
                        for col in range(GRID_COLS):
                            if len(game_state.grid[row][col]) > 0:
                                card_x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
                                card_y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
                                top_card_layer = game_state.grid[row][col][-1][1]
                                for layer, (card_type, card_layer) in enumerate(game_state.grid[row][col]):
                                    card_y_offset = card_y - (top_card_layer - card_layer) * LAYER_OFFSET
                                    if (
                                            card_x <= x <= card_x + CARD_WIDTH
                                            and card_y_offset <= y <= card_y_offset + CARD_HEIGHT
                                            and layer == len(game_state.grid[row][col]) - 1
                                    ):
                                        # 检查槽位是否已满
                                        if len(game_state.slots) >= SLOT_COLS:
                                            game_state.game_over = True
                                            continue


                                        # 取出顶层卡片
                                        card = game_state.grid[row][col].pop()[0]
                                        target_x = SLOT_LEFT + len(game_state.slots) * (CARD_WIDTH + 5)
                                        target_y = SLOT_TOP


                                        # 设置移动动画
                                        game_state.moving_card = (card, card_x, card_y_offset, target_x, target_y)
                                        game_state.move_steps = 0
                                        # 注意：这里不再立即添加到槽位，而是在移动动画结束后添加


    # 处理移动动画
    if game_state.moving_card and game_state.move_steps < MOVE_TOTAL_STEPS:
        game_state.move_steps += 1
        if game_state.move_steps == MOVE_TOTAL_STEPS:
            # 移动动画结束，将卡片添加到槽位
            card, _, _, _, _ = game_state.moving_card
            game_state.slots.append(card)
            game_state.moving_card = None


            # 检查连续三个相同卡片
            if len(game_state.slots) >= 3 and game_state.slots[-1] == game_state.slots[-2] == game_state.slots[-3]:
                # 设置消除动画
                eliminate_indices = [len(game_state.slots) - 3, len(game_state.slots) - 2, len(game_state.slots) - 1]
                eliminate_cards = []
                for idx in eliminate_indices:
                    x = SLOT_LEFT + idx * (CARD_WIDTH + 5)
                    y = SLOT_TOP
                    eliminate_cards.append((game_state.slots[idx], x, y))
                game_state.eliminating_cards = eliminate_cards
                game_state.eliminate_steps = 0


            # 再次检查槽位是否已满
            if len(game_state.slots) >= SLOT_COLS:
                game_state.game_over = True


            # 检查胜利条件
            if game_state.check_victory():
                game_state.game_won = True
                game_state.game_over = True


    # 处理消除动画
    if game_state.eliminating_cards and game_state.eliminate_steps < ELIMINATE_TOTAL_STEPS:
        game_state.eliminate_steps += 1
        if game_state.eliminate_steps == ELIMINATE_TOTAL_STEPS:
            # 消除动画结束，移除卡片
            for card, x, y in game_state.eliminating_cards:
                # 在卡片位置创建礼炮爆炸效果
                game_state.create_fireworks(x + CARD_WIDTH // 2, y + CARD_HEIGHT // 2)
            del game_state.slots[-3:]
            game_state.score += 1
            game_state.eliminating_cards = []
            game_state.elimination_count += 1  # 增加消除计数


            # 每消除一次增加一次撤销机会
            if game_state.elimination_count % 1 == 0:
                game_state.gain_undo_chance()
                game_state.gain_umbrella_charge()  # 每消除一次增加一次萝卜保护伞使用次数


    # 更新礼炮粒子
    game_state.update_particles()


    # 渲染界面
    render_background(game_state, background_manager)
    render_grid(game_state)
    render_slot_background()
    render_slots(game_state)
    render_animations(game_state)
    render_status(game_state, restart_button)


    pygame.display.flip()
    clock.tick(120)


pygame.quit()